package com.attunlcok.unlock.controller;

import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

import com.attunlcok.common.annotation.Anonymous;
import com.attunlcok.unlock.constant.UnlockStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.attunlcok.common.core.domain.AjaxResult;
import com.attunlcok.unlock.domain.AttUnlockRecord;
import com.attunlcok.unlock.service.IAttUnlockRecordService;
import com.attunlcok.common.utils.DateUtils;
import com.attunlcok.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.attunlcok.unlock.service.IAttUnlockOrderService;

/**
 * 解锁结果回调处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/unlock")
public class AttUnlockResultController {
    private static final Logger log = LoggerFactory.getLogger(AttUnlockResultController.class);

    @Autowired
    private IAttUnlockRecordService unlockRecordService;

    @Autowired
    private IAttUnlockOrderService attUnlockOrderService;

    /**
     * 处理解锁结果回调
     */
    @Anonymous
    @PostMapping("/result")
    public AjaxResult handleUnlockResult(@RequestBody UnlockResult result) {
        log.info("收到解锁结果回调 - ID: {}, IMEI: {}, 成功: {}, 消息: {}", 
            result.getId(), result.getImei(), result.isSuccess(), result.getMessage());

        try {
            // 根据ID查询解锁记录
            AttUnlockRecord existingRecord = unlockRecordService.selectAttUnlockRecordById(result.getId());

            if (existingRecord == null) {
                return AjaxResult.error("未找到对应的解锁记录");
            }

            // 更新解锁记录状态
            String newStatus;
            if (result.isSuccess()) {
                // 如果成功，设置为已确认邮件状态
                newStatus = UnlockStatus.CONFIRMED;
            } else if (result.getMessage() != null && result.getMessage().contains("technical issues")) {
                // 如果是技术原因失败，设置为技术失败状态
                newStatus = UnlockStatus.TECH_FAILED;
            } else {
                // 其他失败情况
                newStatus = UnlockStatus.FAILED;
            }

            existingRecord.setUnlockStatus(newStatus);
            existingRecord.setUnlockTime(DateUtils.getNowDate());
            existingRecord.setRemark(result.getMessage());
            unlockRecordService.updateAttUnlockRecord(existingRecord);


            return AjaxResult.success();
        } catch (Exception e) {
            log.error("处理解锁结果回调时发生错误", e);
            return AjaxResult.error("处理回调失败");
        }
    }

    /**
     * 查询IMEI的最新解锁记录
     * 
     * @param imeis IMEI列表，用英文逗号分隔
     * @return 解锁记录列表
     */
    @Anonymous
    @GetMapping("/latest")
    public AjaxResult getLatestUnlockRecords(@RequestParam("imeis") String imeis) {
        if (StringUtils.isEmpty(imeis)) {
            return AjaxResult.error("IMEI列表不能为空");
        }

        try {
            List<String> imeiList = Arrays.asList(imeis.split(","));
            List<AttUnlockRecord> resultList = new ArrayList<>();

            for (String imei : imeiList) {
                // 查询每个IMEI的记录
                AttUnlockRecord query = new AttUnlockRecord();
                query.setImei(imei.trim());
                List<AttUnlockRecord> records = unlockRecordService.selectAttUnlockRecordList(query);
                
                // 如果有记录，取最新的一条
                if (!records.isEmpty()) {
                    // 假设记录按时间倒序排列，取第一条
                    resultList.add(records.get(0));
                }
            }

            return AjaxResult.success(resultList);
        } catch (Exception e) {
            log.error("查询IMEI解锁记录时发生错误", e);
            return AjaxResult.error("查询失败");
        }
    }
}

/**
 * 解锁结果数据类
 */
class UnlockResult {
    private Long id;
    private String imei;
    private boolean success;
    private String message;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getImei() {
        return imei;
    }

    public void setImei(String imei) {
        this.imei = imei;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
} 